package com.mes.controller.printer;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckSQLParamsUtil {
	private static final String regString = "\\{(.*?)\\}";
	
	/**
	 * 解析SQL，返回查询条件
	 * @param sql
	 * @param params
	 * @param bool 是否生成可执行SQL
	 * @return
	 */
	public static Object[] parseSql(String sql, Map<String, Object> params, boolean bool) {
		String querySql = sql;
		Map<String, Object> values = checkParams(sql, params);
		
		for (String code : values.keySet()) {
			if (bool) {
				querySql = querySql.replace("{" + code + "}", ":" + code);
			} else {
				querySql = querySql.replace("{" + code + "}", "'1'");
			}
		}
		return new Object[]{querySql, values};
	}
	
	private static Map<String, Object> checkParams(String html, Map<String, Object> params) {
		Map<String, Object> map = new HashMap<String, Object>();
		Object value = null;
		
        Pattern pattern = Pattern.compile(regString);
        Matcher matcher = pattern.matcher(html);
        
        if (matcher.find()) {
            matcher.reset();
            String code = null;
            
            while (matcher.find()) {
            	code = matcher.group(0).replace("{", "").replace("}", "");
            	if (params != null) {
	            	if (code.split("\\.").length > 1) {
	            		value = params.get(code.split("\\.")[1]);
	            	} else {
	            		value = params.get(code);
	            	}
            	} else {
            		value = "";
            	}
                map.put(code, value);
            }
        }
        return map;
    }
}